<template>
  <div class="time-selector-container">
    <div class="time-input-wrapper" @click="toggleDropdown" ref="inputWrapper">
      <input
        :value="displayValue"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
        type="text"
        :placeholder="placeholder"
        :class="['time-input', inputClass]"
        readonly
      />
      <div class="time-input-icon">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="10"/>
          <polyline points="12,6 12,12 16,14"/>
        </svg>
      </div>
    </div>
    
    <div v-if="showDropdown" class="time-dropdown" ref="dropdown">
      <div class="time-columns">
        <div class="time-column">
          <div class="column-header">时</div>
          <div class="column-content">
            <div
              v-for="hour in hours"
              :key="`hour-${hour}`"
              :class="['time-option', { active: selectedHour === hour }]"
              @click="selectHour(hour)"
            >
              {{ String(hour).padStart(2, '0') }}
            </div>
          </div>
        </div>
        
        <div class="time-column">
          <div class="column-header">分</div>
          <div class="column-content">
            <div
              v-for="minute in minutes"
              :key="`minute-${minute}`"
              :class="['time-option', { active: selectedMinute === minute }]"
              @click="selectMinute(minute)"
            >
              {{ String(minute).padStart(2, '0') }}
            </div>
          </div>
        </div>
        
        <div class="time-column">
          <div class="column-header">秒</div>
          <div class="column-content">
            <div
              v-for="second in seconds"
              :key="`second-${second}`"
              :class="['time-option', { active: selectedSecond === second }]"
              @click="selectSecond(second)"
            >
              {{ String(second).padStart(2, '0') }}
            </div>
          </div>
        </div>
      </div>
      
      <div class="time-actions">
        <button @click="clearTime" class="time-btn time-btn-clear">清空</button>
        <button @click="confirmTime" class="time-btn time-btn-confirm">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'

interface Props {
  modelValue?: string
  placeholder?: string
  inputClass?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '选择时间',
  inputClass: ''
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
}>()

const showDropdown = ref(false)
const inputWrapper = ref<HTMLElement>()
const dropdown = ref<HTMLElement>()

const selectedHour = ref<number>(0)
const selectedMinute = ref<number>(0)
const selectedSecond = ref<number>(0)

// 生成选项数组
const hours = computed(() => Array.from({ length: 24 }, (_, i) => i))
const minutes = computed(() => Array.from({ length: 60 }, (_, i) => i))
const seconds = computed(() => Array.from({ length: 60 }, (_, i) => i))

// 显示值
const displayValue = computed(() => {
  if (!props.modelValue) return ''
  return props.modelValue
})

// 解析时间字符串
const parseTimeString = (timeStr: string) => {
  if (!timeStr) return { hour: 0, minute: 0, second: 0 }
  
  const parts = timeStr.split(':')
  return {
    hour: parseInt(parts[0]) || 0,
    minute: parseInt(parts[1]) || 0,
    second: parseInt(parts[2]) || 0
  }
}

// 格式化时间
const formatTime = (hour: number, minute: number, second: number): string => {
  return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    const { hour, minute, second } = parseTimeString(newValue)
    selectedHour.value = hour
    selectedMinute.value = minute
    selectedSecond.value = second
  } else {
    selectedHour.value = 0
    selectedMinute.value = 0
    selectedSecond.value = 0
  }
}, { immediate: true })

const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
  if (showDropdown.value) {
    // 滚动到当前选中的时间
    setTimeout(() => {
      scrollToSelectedTime()
    }, 100)
  }
}

const selectHour = (hour: number) => {
  selectedHour.value = hour
  // 实时更新显示值，但不关闭弹框
  updateDisplayValue()
}

const selectMinute = (minute: number) => {
  selectedMinute.value = minute
  // 实时更新显示值，但不关闭弹框
  updateDisplayValue()
}

const selectSecond = (second: number) => {
  selectedSecond.value = second
  // 实时更新显示值，但不关闭弹框
  updateDisplayValue()
}

// 更新显示值
const updateDisplayValue = () => {
  const newValue = formatTime(selectedHour.value, selectedMinute.value, selectedSecond.value)
  emit('update:modelValue', newValue)
  emit('change', newValue)
}

const clearTime = () => {
  selectedHour.value = 0
  selectedMinute.value = 0
  selectedSecond.value = 0
  const newValue = ''
  emit('update:modelValue', newValue)
  emit('change', newValue)
  showDropdown.value = false
}

const confirmTime = () => {
  // 如果当前没有值，但有选中的时分秒，需要更新值
  if (!props.modelValue && (selectedHour.value !== 0 || selectedMinute.value !== 0 || selectedSecond.value !== 0)) {
    updateDisplayValue()
  }
  // 如果当前没有值且选中的是默认的00:00:00，也要设置这个值
  else if (!props.modelValue) {
    updateDisplayValue()
  }
  showDropdown.value = false
}

const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  const value = target.value
  
  // 验证时间格式 HH:MM:SS
  const timeRegex = /^([01]?[0-9]|2[0-3]):([0-5]?[0-9]):([0-5]?[0-9])$/
  if (timeRegex.test(value)) {
    const { hour, minute, second } = parseTimeString(value)
    selectedHour.value = hour
    selectedMinute.value = minute
    selectedSecond.value = second
    emit('update:modelValue', value)
    emit('change', value)
  }
}

const handleFocus = () => {
  // 在聚焦时也可以显示下拉框
}

const handleBlur = () => {
  // 不在blur时自动关闭下拉框，只通过点击外部或按钮关闭
}

// 滚动到选中的时间
const scrollToSelectedTime = () => {
  if (!dropdown.value) return
  
  const columns = dropdown.value.querySelectorAll('.column-content')
  const values = [selectedHour.value, selectedMinute.value, selectedSecond.value]
  
  columns.forEach((column, index) => {
    const activeOption = column.querySelector('.time-option.active') as HTMLElement
    if (activeOption) {
      activeOption.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  })
}

// 点击外部关闭下拉框
const handleClickOutside = (event: Event) => {
  const target = event.target as Node
  
  // 如果点击的是输入框区域，不关闭
  if (inputWrapper.value && inputWrapper.value.contains(target)) {
    return
  }
  
  // 如果点击的是下拉框内部（包括时间选项），不关闭
  if (dropdown.value && dropdown.value.contains(target)) {
    return
  }
  
  // 其他情况才关闭下拉框
  showDropdown.value = false
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.time-selector-container {
  position: relative;
  width: 100%;
}

.time-input-wrapper {
  position: relative;
  cursor: pointer;
}

.time-input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.time-input:focus {
  outline: none;
  border-color: #1e40af;
  box-shadow: 0 0 0 2px rgba(30, 64, 175, 0.1);
}

.time-input:hover {
  border-color: #4b5563;
}

.time-input-icon {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
  pointer-events: none;
}

.time-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  margin-top: 4px;
}

.time-columns {
  display: flex;
  max-height: 160px;
}

.time-column {
  flex: 1;
  border-right: 1px solid #e5e7eb;
}

.time-column:last-child {
  border-right: none;
}

.column-header {
  padding: 6px;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  text-align: center;
  font-weight: 500;
  font-size: 12px;
  color: #374151;
}

.column-content {
  max-height: 120px;
  overflow-y: auto;
}

.column-content::-webkit-scrollbar {
  width: 4px;
}

.column-content::-webkit-scrollbar-track {
    background-color: var(--webkit-track-color);
    border-radius: 4px;
}
/* 滚动条滑块 */
.column-content::-webkit-scrollbar-thumb {
    background-color: var(--webkit-thumb-color);
    border-radius: 4px;
}
/* 滚动条滑块 hover 状态 */
.column-content::-webkit-scrollbar-thumb:hover {
    background-color: var(--webkit-thumb-hover-color);
}
.time-option {
  padding: 4px 8px;
  cursor: pointer;
  text-align: center;
  font-size: 13px;
  transition: background-color 0.2s;
}

.time-option:hover {
  background-color: #f3f4f6;
}

.time-option.active {
  background-color: #1e40af;
  color: white;
}

.time-actions {
  display: flex;
  justify-content: space-between;
  padding: 6px;
  border-top: 1px solid #e5e7eb;
  gap: 6px;
}

.time-btn {
  flex: 1;
  padding: 4px 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 11px;
  transition: all 0.2s;
}

.time-btn-clear {
  color: #6b7280;
}

.time-btn-clear:hover {
  border-color: #6b7280;
  background-color: #f9fafb;
}

.time-btn-confirm {
  background-color: #1e40af;
  color: white;
  border-color: #1e40af;
}

.time-btn-confirm:hover {
  background-color: #1d4ed8;
}

/* 暗黑模式支持 */
.dark .time-input {
  background-color: #ffffff !important;
  color: #374151 !important;
  border-color: #d1d5db !important;
}

.dark .time-input:focus {
  border-color: #1e40af !important;
  box-shadow: 0 0 0 2px rgba(30, 64, 175, 0.1) !important;
}

.dark .time-input:hover {
  border-color: #4b5563 !important;
}

.dark .time-dropdown {
  background-color: white;
  border-color: #d1d5db;
}

.dark .column-header {
  background-color: #f9fafb;
  color: #374151;
}

.dark .time-option:hover {
  background-color: #f3f4f6;
}

.dark .time-btn {
  background-color: white;
  color: #374151;
}

.dark .time-btn-confirm {
  background-color: #1e40af;
  color: white;
}
</style> 